#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys

from setup import PACKAGE_DIR
from setup import TEST_SUITE
from setup import PackageFinder


# This is Python 2.4 compatible whereas 'load_tests' protocol is not.
def load_tests(module):
    """Loads all tests from a given module or package (including tests
    in submodules) and returns a TestSuite object.

    """
    loader = unittest.defaultTestLoader
    all_tests = unittest.TestSuite()
    if hasattr(module, '__path__'):
        for name in os.listdir(module.__path__[0]):
            if name.endswith('.py') and name != '__init__.py':
                name = module.__name__ + '.' + name[:-3]
                __import__(name)
                submodule = sys.modules[name]
                tests = load_tests(submodule)
                all_tests.addTests(tests)
    else:
        tests = loader.loadTestsFromModule(module)
        all_tests.addTests(tests)
    return all_tests


if __name__ == '__main__':
    # Register import hook.
    sys.meta_path.append(PackageFinder(PACKAGE_DIR))

    # Import unittest, load test cases, run tests.
    import adm._compatibility._unittest as unittest
    __import__(TEST_SUITE)
    test_package = sys.modules[TEST_SUITE]
    all_tests = load_tests(test_package)
    unittest.main(defaultTest='all_tests')

